package com.sy.musicapp.service

import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.media.MediaPlayer
import android.os.Binder
import android.os.IBinder
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.core.app.NotificationCompat
import com.sy.musicapp.MainActivity
import com.sy.musicapp.MyIntent
import com.sy.musicapp.R
import com.sy.musicapp.Util

class MediaPlayerService : Service() {

    private lateinit var mediaPlayer: MediaPlayer
    private lateinit var musicBinder: MusicBinder
    private var isSetData: Boolean = false //是否设置资源
    private lateinit var notification: Notification

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Util.showLog("startCommand")
        return super.onStartCommand(intent, flags, startId)
    }

    @OptIn(ExperimentalComposeUiApi::class)
    override fun onCreate() {
        super.onCreate()
        //初始化数据
        mediaPlayer = MediaPlayer()
        musicBinder = MusicBinder()
        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val channel =
            NotificationChannel("MusicService", "前台通知", NotificationManager.IMPORTANCE_DEFAULT)
        manager.createNotificationChannel(channel)
        val intent = MyIntent<MainActivity>(this)
        val pi = PendingIntent.getActivity(this, 0, intent, 0)
        notification = NotificationCompat.Builder(this, channel.id)
            .setContentTitle("音乐播放")
            .setContentText("等待播放")
            .setSmallIcon(R.drawable.keli)
            .setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.keli_3))
            .setContentIntent(pi)
            .build()
        startForeground(1, notification)
    }

    private fun playMusic(path: String, musicStateListener: MusicStateListener) {
        try {
            //设置资源
            mediaPlayer.reset()
            mediaPlayer.setDataSource(path)

            //异步缓冲准备及监听
            mediaPlayer.prepareAsync()
            mediaPlayer.setOnPreparedListener {
                isSetData = true
                mediaPlayer.start()
                musicStateListener.prepared()
            }

            //播放结束监听
            mediaPlayer.setOnCompletionListener {
                if (!mediaPlayer.isLooping) {
                    isSetData = false
                    musicStateListener.completed()
                }
            }
            mediaPlayer.setOnErrorListener(MediaPlayer.OnErrorListener { _, _, _ ->
                musicStateListener.onError("mediaplayer error")
                return@OnErrorListener true
            })
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        mediaPlayer.stop()
        mediaPlayer.release()
        isSetData = false
    }


    inner class MusicBinder : Binder() {

        //开始播放
        fun start(path: String?, musicStateListener: MusicStateListener) {
            if (path == null) {
                musicStateListener.onError("播放地址为空")
                return
            }
            resetState()
            playMusic(path, musicStateListener)
        }

        //获取资源状态
        fun isSetData(): Boolean {
            return isSetData
        }

        fun resetState() {
            mediaPlayer.reset()
            isSetData = false
        }

        fun setLoop(loop: Boolean) {
            mediaPlayer.isLooping = loop
        }

        //获取当前播放状态
        fun isPlaying(): Boolean {
            return mediaPlayer.isPlaying
        }

        //继续播放
        fun play(): Boolean {
            if (isSetData && !mediaPlayer.isPlaying) {
                mediaPlayer.start()
            }
            return mediaPlayer.isPlaying
        }

        //暂停播放
        fun pause(): Boolean {
            if (isSetData && mediaPlayer.isPlaying) {
                mediaPlayer.pause()
            }
            return mediaPlayer.isPlaying
        }

        /**
         * 获取歌曲当前时长位置
         * 如果返回-1，则mediaplayer没有缓冲歌曲
         * @return
         */
        fun getCurrent(): Int {
            return if (isSetData) {
                mediaPlayer.currentPosition
            } else {
                0
            }
        }

        /**
         * 获取歌曲总时长
         * 如果返回-1，则mediaplayer没有缓冲歌曲
         * @return
         */
        fun getDuration(): Int {
            return if (isSetData) {
                mediaPlayer.duration
            } else {
                -1
            }
        }


        fun seekTo(time: Int) {
            mediaPlayer.seekTo(time)
        }

    }

    override fun onBind(intent: Intent): IBinder {
        return musicBinder
    }

    interface MusicStateListener {
        fun prepared()
        fun completed(isPrev: Boolean = false)
        fun onError(msg: String)
    }

}